<template>
  <div class="container py-3">
    <ActionsBar
      :selectedItems="selectedItems"
      @remove="handleRemove"
      @rename="showModel = true"
      @files-choose="chooseFiles = $event" />
    <div class="d-flex justify-content-between align-items-center py-2">
      <h6 class="text-muted mb-0">文件</h6>
      <SortToggler @sort-change="handleSortChange($event)" />
    </div>
    <teleport to="#search-form">
      <SearchForm v-model="query.q" />
    </teleport>
    <DropZone @files-dropped="chooseFiles = $event" :showMessage="!files.length">
      <FilesList
        :files="files"
        @select-change="handleSelectChange($event)"
        :selected="selectedItems" />
    </DropZone>
    <app-model
      title="文件重命名"
      :show="showModel && selectedItems.length === 1"
      @hide="showModel = false">
      <FileRenameForm
        :file="selectedItems[0]"
        @file-updated="handleFileUpdated($event)"
        @close="showModel = false" />
    </app-model>
    <app-toast
      :show="toast.show"
      :message="toast.message"
      type="success"
      position="bottom-left"
      @hide="toast.show = false" />
    <UploaderPopup
      :files="chooseFiles"
      @update-complete="handleUploadComplete"
      @handleSelectChange="handleSelectChange" />
  </div>
</template>

<script setup>
import ActionsBar from '../components/ActionsBar.vue'
import FilesList from '../components/files/FilesList.vue'
import SortToggler from '../components/SortToggler.vue'
import axios from 'axios'
import SearchForm from '../components/SearchForm.vue'
import FileRenameForm from '../components/files/FileRenameForm.vue'
import DropZone from '../components/uploader/file-chooser/DropZone.vue'
import UploaderPopup from '../components/uploader/popup/UploaderPopup.vue'
import { ref, onMounted, reactive, watch, watchEffect, getCurrentInstance, provide } from 'vue'

const { proxy } = getCurrentInstance()

const files = ref([])
const selectedItems = ref([])
const showModel = ref(false)
const chooseFiles = ref([])

watch(
  () => chooseFiles.value,
  () => {
    console.log(chooseFiles.value)
  }
)

const query = reactive({
  _sort: 'name',
  _order: 'asc',
  q: '',
})

const toast = reactive({
  show: false,
  message: '',
})

//watchEffect 和 watch对比
watchEffect(async () => {
  const { data } = await axios.get(`http://localhost:3030/files?${new URLSearchParams(query)}`)
  files.value = data
})

// watch(
//   () => query._order,
//   async () => {
//     const { data } = await axios.get(`http://localhost:3030/files?${new URLSearchParams(query)}`)
//     files.value = data
//   },
//   {
//     immediate: true,
//   }
// )

const handleSelectChange = (items) => {
  // console.log(items)
  selectedItems.value = Array.from(items)
}

const handleSortChange = (payload) => {
  // console.log(payload)
  query._sort = payload.column
  query._order = payload.order
}

provide('setSelectedItem', handleSelectChange)

const handleRemove = () => {
  if (confirm('Are you sure!!!')) {
    selectedItems.value.forEach((item) => removeItem(item, files))
    toast.show = true
    toast.message = '您选择的文件已删除'
  }
}

const removeItem = async (item, files) => {
  try {
    const response = await axios.delete(`http://localhost:3030/files/${item.id}`)
    console.log(response)
    if (response.status == 200) {
      const index = files.value.findIndex((file) => file.id === item.id)
      files.value.splice(index, 1)
    }
  } catch (error) {
    proxy.$cl(error, 'pink')
  }
}

const handleFileUpdated = (file) => {
  const oldFile = selectedItems.value[0]
  const index = files.value.findIndex((file) => file.id === oldFile.id)
  files.value.splice(index, 1, file)
  toast.show = true
  toast.message = '文件名修改成功'
}

const handleUploadComplete = (item) => {
  files.value.push(item)
}
</script>

<style></style>
